package com.yanti.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yanti.common.constant.RedisConstants;
import com.yanti.domain.entity.UserDailyQuestionCount;
import com.yanti.mapper.UserDailyQuestionCountMapper;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.yanti.service.UserDailyQuestionCountService;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.HashMap;
import java.util.List;


/**
 * 用户每日题目刷题表(UserDailyQuestionCount)表服务实现类
 *
 * @author luo
 * @since 2025-05-21 18:48:37
 */
@Service("userDailyQuestionCountService")
@Slf4j
public class UserDailyQuestionCountServiceImpl extends ServiceImpl<UserDailyQuestionCountMapper, UserDailyQuestionCount> implements UserDailyQuestionCountService {

    @Resource
    private UserDailyQuestionCountMapper userDailyQuestionCountMapper;
    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    // todo 批量查询优化，事务的细粒度
    @Override
    public Boolean updateUserDailyQuestionCount4DB(String uid, List<Long> questionIds) {
        // 获取当前日期
        LocalDate localDate = LocalDate.now();
        Date utilDate = Date.from(localDate.atStartOfDay(ZoneId.systemDefault()).toInstant());
        // 获取当前日期的字符串格式
        String date = localDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        // 构建redis的键，在redis中采用了hash 结构，key为uid和date的组合，value为questionId和count的组合
        // 示例键：user:question:count:uid:date
        String key = RedisConstants.buildUserQuestionCountKey(uid, date);
        try {
            for(Long questionId : questionIds){
                // 先判断是否存在，存在则更新，不存在则新增
                QueryWrapper<UserDailyQuestionCount> queryWrapper = new QueryWrapper<UserDailyQuestionCount>()
                        .eq("uid", uid)
                        .eq("date", utilDate)
                        .eq("question_id", questionId);
                UserDailyQuestionCount userDailyQuestionCount = userDailyQuestionCountMapper.selectOne(queryWrapper);
                if(userDailyQuestionCount != null){
                    // 存在，更新
                    userDailyQuestionCount.setCount(userDailyQuestionCount.getCount() + 1);
                    userDailyQuestionCountMapper.updateById(userDailyQuestionCount);
                }else{
                    // 不存在，新增
                    userDailyQuestionCount = new UserDailyQuestionCount();
                    userDailyQuestionCount.setUid(uid);
                    userDailyQuestionCount.setDate(utilDate);
                    userDailyQuestionCount.setQuestionId(questionId);
                    userDailyQuestionCount.setCount(1L);
                    userDailyQuestionCountMapper.insert(userDailyQuestionCount);
                }
            }
        } catch (Exception e) {
            log.error("更新或插入每日刷题记录失败: {}", e.getMessage());
            return false;
        }
        // 删除缓存中的数据
        try {
            // 删除指定用户指定日期的所有题目计数缓存
            redisTemplate.delete(key);
            log.info("成功删除Redis缓存数据，key: {}", key);
        } catch (Exception e) {
            log.error("删除Redis缓存数据失败: {}", e.getMessage());
        }
        return true;
    }

    @Override
    public HashMap<Long, Integer> getUserTodayQuestionCount(String uid) {
        // 获取当前日期
        LocalDate localDate = LocalDate.now();
        Date utilDate = Date.from(localDate.atStartOfDay(ZoneId.systemDefault()).toInstant());
        // 从数据库获取用户刷题记录
        QueryWrapper<UserDailyQuestionCount> queryWrapper = new QueryWrapper<UserDailyQuestionCount>()
                .eq("uid", uid)
                .eq("date", utilDate);
        List<UserDailyQuestionCount> userDailyQuestionCountList = userDailyQuestionCountMapper
                .selectList(queryWrapper);
        HashMap<Long, Integer> questionCountMap = new HashMap<>();
        if(userDailyQuestionCountList != null && userDailyQuestionCountList.size() > 0){
            for(UserDailyQuestionCount userDailyQuestionCount : userDailyQuestionCountList){
                questionCountMap.put(userDailyQuestionCount.getQuestionId(), userDailyQuestionCount.getCount().intValue());
                log.debug("用户 {} 在 {} 刷题了 {} 题", uid, utilDate, userDailyQuestionCount.getCount());
            }
        }
        return questionCountMap;
    }
}